import React, { useEffect, useState } from "react";
import { createConnection } from "./chat";
import { showNotification } from "./notifications";
import useEffectEvent from "@/hooks/useEffectEvent";

const serverUrl = "http://localhost:8080";
interface ChatRoomProps {
  roomId: string;
  theme: string;
}
const ChatRoom: React.FC<ChatRoomProps> = ({ roomId, theme }) => {
  const onConnected = useEffectEvent(() => {
    showNotification("Connected", theme);
  });

  useEffect(() => {
    const connection = createConnection(serverUrl, roomId);

    connection.on("connected", () => {
      onConnected();
    });
    connection.connect();

    return () => {
      connection.disconnect();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [roomId]);

  return (
    <>
      <h1>欢迎来{roomId}房间！</h1>
    </>
  );
};

function Chat() {
  const [roomId, setRoomId] = useState("general");
  const [isDark, setIsDark] = useState(false);

  return (
    <>
      <label>
        选择聊天室：
        <select value={roomId} onChange={e => setRoomId(e.target.value)}>
          <option value="general">所有</option>
          <option value="travel">旅游</option>
          <option value="music">音乐</option>
        </select>
      </label>
      <label>
        <input type="checkbox" checked={isDark} onChange={e => setIsDark(e.target.checked)} />
        使用黑色主题
      </label>
      <hr />
      <ChatRoom roomId={roomId} theme={isDark ? "dark" : "light"} />
    </>
  );
}
export default Chat;
